import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Button, FormInstance, Form, Modal } from 'antd';
import React, { useState, useEffect, useRef, useImperativeHandle, forwardRef } from 'react';
import { useModel } from 'umi';
import ProForm, { ProFormText } from '@ant-design/pro-form';
import { OptType } from '@/utils/constants';
import { isNull, showMsg, MsgType } from '@/utils/utils';
import { 
  getPatientList,
  getPatientHospitalizationInfo,
  getDischargeStatus
}  from '@/services/order/api';
import '../style.less';

interface MyProps {
  id: string;
  type: string;
  onSubmit: Function;
  goodsRef: Object;
  settRef: Object;
  setInfo: Function;
  orderDetail: Object;
}

const { confirm } = Modal;

const Result: React.FC<MyProps> = forwardRef((props, ref) => {
  const { onSubmit, type, goodsRef, settRef, setInfo, orderDetail={} } = props;
  const [loading, setLoading] = useState(false);
  const formRef = useRef<FormInstance>();
  // 患者信息
  const [patientInfo, setPatientInfo] = useState<ORDERAPI.PatientInfo>({} as ORDERAPI.PatientInfo);

  useEffect(() => {
    setPatientInfo(orderDetail)
  }, [orderDetail])

  // 暴露的子组件方法，给父组件调用
  useImperativeHandle(ref, () => ({
    clear: () => {
      setPatientInfo({});
      formRef.current?.resetFields();
    }
  }))

  // 查询患者信息
  const fetchPatientList = async (data: { identity_no?: string;}) => {
    try {
      const list = await getPatientList(data);

      if(!list.length) {
        showMsg('患者信息不存在!', MsgType.ERROR);
        return;
      }
      initPage(list[0]);
    } catch (error) {
     showMsg(error?.data?.errmsg); 
    }
  }

  // 患者住院信息
  const fetchPatientHospitalizationInfo = async (data: { visit_no: string }) => {
    const list = await getPatientHospitalizationInfo(data);
    const info = list[0]
    if (!info) {
      showMsg('未找到患者信息', MsgType.INFO);
      setPatientInfo({} as ORDERAPI.PatientInfo);
      setInfo({});
      return;
    }
    checkOrder(info);
  }

  function showConfirm() {
    const result = goodsRef.current.isNull();
    console.log('result', result);
    if (!result) {
      confirm({
        title: '当前有未保存的订单信息，是否保存？',
        icon: <ExclamationCircleOutlined />,
        okText: '保存',
        cancelText: '放弃',
        onOk() {
          onSubmit();
        },
        onCancel() {
          console.log('Cancel');
          setPatientInfo({});
          goodsRef.current.clear();
          settRef.current.clear();
          formRef.current?.setFieldsValue({ identity_no: null });
          setInfo({});
        },
      });
    } else {
      setPatientInfo({});
      goodsRef.current.clear();
      settRef.current.clear();
      formRef.current?.setFieldsValue({ identity_no: null });
      setInfo({});
    }
    
  }

  // 判断是否出院办结
  const checkOrder = async(info) => {
    const data = await getDischargeStatus({
      patient_id: info.patient_id,
      admission_num: info.visit_no
    });
    
    if (['W'].includes(data.manager_status)) {
      showMsg('存在处理中的出院办结信息', MsgType.INFO);
    } else if (['F'].includes(data.manager_status)) {
      showMsg('患者已办理出院，无法创建订单', MsgType.INFO);
    } else {
      initPage(info);
    }
  }

  const initPage = (info) => {
    goodsRef.current.addLine();
    const result = Object.assign({}, info, { mobile: info.contact_tel_no});
    setPatientInfo(Object.assign({}, result));
    setInfo(Object.assign({}, result));
    formRef.current?.setFieldsValue({
      patient_name: info.patient_name
    });
  }

  // console.log('ygData', orderObj, loading)
  return (
    <ProForm 
      className="order-pro-form service-record patient-form"
      style={{ padding: '0px 20px' }}
        submitter={
          {
            searchConfig: {
              submitText: isNull(patientInfo.patient_id) ? '查询' : '更换患者'
            },
            submitButtonProps: {
              style: {
                display: type === OptType.ADD ? 'block' : 'none'
              },
              disabled: type === OptType.EDIT
            },
            resetButtonProps: {
              style: {
                display: 'none'
              }
            },
          }
          //  : false
      } 
      formRef={formRef}
      onFinish={async (values) => {
        console.log(values);
        if (!isNull(patientInfo.patient_id)) {
          showConfirm();
          return;
        }
        const { identity_no } = values;
        if (!identity_no) {
          showMsg('请输入身份证或住院号', MsgType.INFO);
          return;
        }
        console.log('identity_no', identity_no.length);
        if (identity_no.length > 5 && identity_no.length < 15) {
          await fetchPatientHospitalizationInfo({
            visit_no: identity_no
          });
        } else if (identity_no.length === 15 || identity_no.length === 18) {
          await fetchPatientList({
            identity_no: identity_no
          });
        } else {
          showMsg('身份证或住院号输入有误', MsgType.INFO);
        }
      }}
      layout='inline'>
      <ProForm.Group>
        {
          (type === OptType.ADD && isNull(patientInfo.patient_id)) ? <ProFormText
            disabled={type === OptType.EDIT}
            label="身份证/住院号"
            name="identity_no"
            placeholder="输入完整身份证号/住院号"
            width={200}
            fieldProps={{
              onPressEnter: (e) => {
                e.preventDefault();
                formRef.current?.submit()
              }
            }}
          /> : <Form.Item label="身份证/住院号">
            <span>{patientInfo.identity_no}{!isNull(patientInfo.identity_no) && !isNull(patientInfo.visit_no) ? ' / ' : ''}{patientInfo.visit_no}</span>
          </Form.Item>
        }
        {
          patientInfo.patient_id &&
          <>
            <Form.Item label="患者姓名">
              <span>{patientInfo.patient_name}</span>
            </Form.Item>
            <Form.Item label="患者性别">
              <span>{patientInfo.patient_sex_name || '-'}</span>
            </Form.Item>
            <Form.Item label="归属科室" style={{display: patientInfo.dept_name ? 'block' : 'none'}}>
              <span>{patientInfo.dept_name}</span>
            </Form.Item>
          </>
        }
      </ProForm.Group>
    </ProForm>
  );
});

export default Result;
